import { reactive, computed, watch } from 'vue'
import type { PropertyPanelProps, FormConfig } from '../types'
import type Modeling from 'bpmn-js/lib/features/modeling/Modeling'
import type { Moddle } from 'bpmn-moddle'

export function useFormConfig(props: PropertyPanelProps) {
  // 初始化表单配置
  const formConfig = reactive<FormConfig>({
    formKey: '',
    formReadOnly: false,
    formSubmit: true,
    fields: [],
  })

  // 是否显示表单配置
  const showFormConfig = computed(() => {
    return ['bpmn:UserTask', 'bpmn:StartEvent'].includes(props.currentElement?.type || '')
  })

  // 重置表单配置
  const resetFormConfig = () => {
    formConfig.formKey = ''
    formConfig.formReadOnly = false
    formConfig.formSubmit = true
    formConfig.fields = []
  }

  // 更新表单配置
  const updateFormConfig = () => {
    if (!props.currentElement || !showFormConfig.value) {
      resetFormConfig()
      return
    }

    const bo = props.currentElement.businessObject

    // 更新基础属性
    formConfig.formKey = bo.get('flowable:formKey') || ''
    formConfig.formReadOnly = bo.get('flowable:formReadOnly') || false
    formConfig.formSubmit = bo.get('flowable:formSubmit') !== false // 默认为true

    // 更新表单字段
    const extensionElements = bo.extensionElements
    if (extensionElements && extensionElements.values) {
      const formData = extensionElements.values.find(
        (value: any) => value.$type === 'flowable:FormData',
      )

      if (formData && formData.fields) {
        formConfig.fields = formData.fields.map((field: any) => ({
          id: field.id || '',
          name: field.name || '',
          type: field.type || 'string',
          permission: field.permission || 'write',
          required: field.required || false,
          values: field.values || '',
        }))
      } else {
        formConfig.fields = []
      }
    } else {
      formConfig.fields = []
    }
  }

  // 处理表单配置变更
  const handleFormChange = () => {
    if (!props.currentElement || !props.modeler) return

    const modeling = props.modeler.get('modeling') as Modeling
    const moddle = props.modeler.get('moddle') as Moddle

    // 更新基础属性
    modeling.updateProperties(props.currentElement, {
      'flowable:formKey': formConfig.formKey,
      'flowable:formReadOnly': formConfig.formReadOnly,
      'flowable:formSubmit': formConfig.formSubmit,
    })

    // 创建表单字段
    const formFields = formConfig.fields.map((field) => {
      return moddle.create('flowable:FormField', {
        id: field.id,
        name: field.name,
        type: field.type,
        permission: field.permission,
        required: field.required,
        values: field.values,
      })
    })

    // 创建表单数据
    const formData = moddle.create('flowable:FormData', {
      fields: formFields,
    })

    // 获取或创建 extensionElements
    let extensionElements = props.currentElement.businessObject.extensionElements
    if (!extensionElements) {
      extensionElements = moddle.create('bpmn:ExtensionElements', {
        values: [],
      })
    }

    // 移除旧的表单数据
    extensionElements.values = extensionElements.values.filter(
      (value: any) => value.$type !== 'flowable:FormData',
    )

    // 添加新的表单数据
    extensionElements.values.push(formData)

    // 更新 extensionElements
    modeling.updateProperties(props.currentElement, {
      extensionElements: extensionElements,
    })
  }

  // 添加表单字段
  const handleAddFormField = () => {
    formConfig.fields.push({
      id: `field_${Date.now()}`,
      name: '',
      type: 'string',
      permission: 'write',
      required: false,
      values: '',
    })
    handleFormChange()
  }

  // 移除表单字段
  const handleRemoveFormField = (index: number) => {
    formConfig.fields.splice(index, 1)
    handleFormChange()
  }

  // 监听当前元素变化
  watch(
    () => props.currentElement,
    () => {
      updateFormConfig()
    },
    { immediate: true },
  )

  return {
    formConfig,
    showFormConfig,
    handleFormChange,
    handleAddFormField,
    handleRemoveFormField,
  }
}
